﻿/// <reference path="../../libraries/class.js" />
/// <reference path="../../filehandler.js" />
/// <reference path="../../libraries/q.js" />
/// <reference path="hero.js" />
/// <reference path="../encryptor.js" />

var Summoner = (function () {
    var HERO_FILE_NAME = "summonersQuiz.config";
    var hero = new Hero();

    //It is asynchronus so, it returns a promise
    var GetHero = function () {
        var getDeffered = Q.defer();

        var filePromise = FileHandler.readTextFile(HERO_FILE_NAME);
        filePromise.then(function (heroString) {
            var encryptor = new Encryptor();
            var decrypted = encryptor.decrypt(heroString);
            var loadedHero = JSON.parse(decrypted);
            hero = loadedHero || hero;
            getDeffered.resolve(hero);
        }, function (error) {
            getDeffered.reject(error);
        });

        return getDeffered.promise;
    }

    //it returns a promise
    var SaveHero = function (theHero) {
        var saveDeffered = Q.defer();

        var heroToSave = theHero || hero;

        var encryptor = new Encryptor();
        var heroString =  JSON.stringify(heroToSave);
        
        var saveToFile = encryptor.encrypt(heroString);

        var filePromise = FileHandler.writeTextFile(HERO_FILE_NAME, saveToFile);
        filePromise.then(function (success) {
            if (success) { //check if the fileWriter has return true for successfully writing, and propagate it to caller
                saveDeffered.resolve(success);
            }
            else {
                saveDeffered.reject({ message: "The fileWriter didnt return True for successful writing to the file!" });
            }
        }, function (error) {
            saveDeffered.reject(error);
        });

        return saveDeffered.promise;
    }

    return {
        GetHero: GetHero,
        SaveHero: SaveHero
    }
}())


